import 'react-native-get-random-values';
import { MessageStorage } from './messageStorage';

// 生成唯一ID的函数
const generateId = () => {
  return Math.random().toString(36).substring(2) + Date.now().toString(36);
};

type MessageStatus = 'sent' | 'delivered' | 'read';
type FriendRequestStatus = 'pending' | 'accepted' | 'rejected';

interface SocketMessage {
  type: 'friendRequest' | 'friendRequestUpdate' | 'chat' | 'messageStatus' | 'connection' | 'error';
  id: string;
  senderId: string;
  receiverId: string;
  content?: string;
  status?: MessageStatus | FriendRequestStatus;
  timestamp?: number;
  message?: string;
}

interface FriendRequestMessage {
  type: 'friendRequest';
  id: string;
  senderId: string;
  receiverId: string;
  content: string;
  status: FriendRequestStatus;
  timestamp: number;
}

interface MessageStatusUpdate {
  type: 'messageStatus';
  id: string;
  senderId: string;
  receiverId: string;
  status: MessageStatus;
  timestamp: number;
}

let socket: WebSocket | null = null;
let reconnectAttempts = 0;
let heartbeatInterval: NodeJS.Timeout | null = null;
const MAX_RECONNECT_ATTEMPTS = 5;
const INITIAL_RECONNECT_DELAY = 1000;
const MAX_RECONNECT_DELAY = 30000;
const HEARTBEAT_INTERVAL = 30000;

// 心跳检测函数
const startHeartbeat = (ws: WebSocket) => {
  stopHeartbeat(); // 确保先清理之前的心跳检测
  if (ws.readyState === WebSocket.OPEN) {
    heartbeatInterval = setInterval(() => {
      if (ws.readyState === WebSocket.OPEN) {
        ws.send(JSON.stringify({ type: 'ping' }));
      } else {
        stopHeartbeat(); // 如果连接已断开，停止心跳检测
      }
    }, HEARTBEAT_INTERVAL);
  }
};

// 停止心跳检测
const stopHeartbeat = () => {
  if (heartbeatInterval) {
    clearInterval(heartbeatInterval);
    heartbeatInterval = null;
  }
};

// 初始化WebSocket连接
export const initSocket = (userId: string): WebSocket => {
  if (!userId) {
    throw new Error('用户ID不能为空');
  }

  if (socket && socket.readyState === WebSocket.OPEN) {
    return socket;
  }

  const wsUrl = `ws://192.168.137.1:3001?userId=${userId}`;
  socket = new WebSocket(wsUrl);
  
  socket.onopen = () => {
    console.log('WebSocket已连接');
    reconnectAttempts = 0; // 重置重连次数
    startHeartbeat(socket!); // 启动心跳检测
  };

  socket.onerror = (event: Event) => {
    const error = event as ErrorEvent;
    console.error('WebSocket连接错误:', {
      message: error.message,
      type: error.type,
      error: error.error,
      timestamp: new Date().toISOString(),
      readyState: socket?.readyState
    });
    stopHeartbeat();
    // 触发重连机制
    if (socket) {
      socket.close();
    }
  };

  let reconnectTimeout: NodeJS.Timeout | null = null;

socket.onclose = () => {
    console.log('WebSocket连接已关闭');
    stopHeartbeat();
    // 清理之前的重连计时器
    if (reconnectTimeout) {
      clearTimeout(reconnectTimeout);
      reconnectTimeout = null;
    }
    // 尝试重新连接
    if (reconnectAttempts < MAX_RECONNECT_ATTEMPTS) {
      const delay = Math.min(INITIAL_RECONNECT_DELAY * Math.pow(2, reconnectAttempts), MAX_RECONNECT_DELAY);
      reconnectTimeout = setTimeout(() => {
        reconnectAttempts++;
        initSocket(userId);
      }, delay);
    }
  };
  
  socket.onmessage = async (event) => {
    try {
      const data: SocketMessage = JSON.parse(event.data);
      console.log('收到新消息:', data);

      switch (data.type) {
        case 'connection':
          console.log('连接状态:', data.status);
          break;

        case 'error':
          console.error('服务器错误:', data.message);
          break;

        case 'friendRequest': {
          const { senderId, receiverId, content, id } = data;
          if (!senderId || !receiverId) {
            console.error('好友请求缺少必要信息');
            return;
          }

          const requestMessage: FriendRequestMessage = {
            type: 'friendRequest',
            id: id || generateId(), // 优先使用服务器返回的 id，如果没有则生成新的
            senderId,
            receiverId,
            content: content || '新的好友请求',
            status: 'pending',
            timestamp: data.timestamp || Date.now()
          };

          const requestAdded = await MessageStorage.addFriendRequest({
            requestId: requestMessage.id,
            senderId: requestMessage.senderId,
            receiverId: requestMessage.receiverId,
            timestamp: requestMessage.timestamp,
            status: requestMessage.status,
            content: requestMessage.content
          });

          if (requestAdded) {
            console.log('好友请求已存储');
          }
          break;
        }

        case 'friendRequestUpdate':
          const requestUpdated = await MessageStorage.updateFriendRequest({
            requestId: data.id!, // 使用requestId字段
            senderId: data.senderId,
            receiverId: data.receiverId,
            status: data.status as any,
            timestamp: data.timestamp || Date.now(),
            content: data.content || ''
          });
          if (requestUpdated) {
            console.log('好友请求状态已更新');
          }
          break;

        case 'chat':
          if (!data.content) {
            console.error('聊天消息缺少内容');
            return;
          }
          const messageAdded = await MessageStorage.addMessage({
            id: data.id || generateId(),
            senderId: data.senderId,
            receiverId: data.receiverId,
            content: data.content,
            timestamp: data.timestamp || Date.now(),
            status: 'delivered'
          });
          if (messageAdded) {
            console.log('聊天消息已存储');
            // 发送消息已送达的状态更新
            sendMessageStatus(data.id!, data.senderId, 'delivered');
          }
          break;

        case 'messageStatus': {
          const { id, senderId, receiverId, status } = data;
          if (!id || !senderId || !receiverId || !status) {
            console.error('消息状态更新缺少必要信息');
            return;
          }

          if (!['sent', 'delivered', 'read'].includes(status as string)) {
            console.error('无效的消息状态:', status);
            return;
          }

          const messageStatus = status as MessageStatus;
          const statusMessage: MessageStatusUpdate = {
            type: 'messageStatus',
            id,
            senderId,
            receiverId,
            status: messageStatus,
            timestamp: data.timestamp || Date.now()
          };

          const statusUpdated = await MessageStorage.updateMessageStatus(
            statusMessage.id,
            statusMessage.status,
            statusMessage.senderId,
            statusMessage.receiverId
          );

          if (statusUpdated) {
            console.log('消息状态已更新');
          }
          break;
        }

        default:
          console.warn('未知的消息类型:', data.type);
      }
    } catch (error) {
      console.error('消息处理错误:', error);
    }
  };

  socket.onerror = (error) => {
    console.error('WebSocket连接错误:', error);
  };

  socket.onclose = (event) => {
    console.log('WebSocket连接已关闭, code:', event.code, '原因:', event.reason);
    stopHeartbeat(); // 停止心跳检测
    socket = null;

    // 如果不是正常关闭，尝试重连
    if (event.code !== 1000 && reconnectAttempts < MAX_RECONNECT_ATTEMPTS) {
      reconnectAttempts++;
      // 使用指数退避策略计算重连延迟
      const delay = Math.min(
        INITIAL_RECONNECT_DELAY * Math.pow(2, reconnectAttempts - 1),
        MAX_RECONNECT_DELAY
      );
      console.log(`将在 ${delay}ms 后进行第 ${reconnectAttempts} 次重连...`);
      setTimeout(() => {
        initSocket(userId);
      }, delay);
    }
  };

  return socket;
};

// 发送消息状态更新
const sendMessageStatus = async (messageId: string, receiverId: string, status: MessageStatus) => {
  if (!socket || socket.readyState !== WebSocket.OPEN) {
    console.error('WebSocket未连接，无法发送消息状态');
    return false;
  }
  
  // 先更新本地消息状态
  await MessageStorage.updateMessageStatus(messageId, status, receiverId, socket.url.split('userId=')[1]);

  try {
    socket.send(JSON.stringify({
      type: 'messageStatus',
      id: messageId,
      status,
      receiverId
    }));
    return true;
  } catch (error) {
    console.error('发送消息状态失败:', error);
    return false;
  }
};